package com.mk.security.distributed.uaa.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;
import java.util.Arrays;

//授权服务配置
@Configuration
@EnableAuthorizationServer //开启授权服务
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private TokenStore tokenStore;//token存储策略
    @Autowired
    private ClientDetailsService clientDetailsService;//客户端详情服务
    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;//授权码服务
    @Autowired
    private AuthenticationManager authenticationManager;//授权认证管理器
    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;
    @Autowired
    private PasswordEncoder passwordEncoder;



    /**
     * 1、ClientDetailsServiceConfigurer
     * 2、AuthorizationServerSecurityConfigurer
     * 3、AuthorizationServerEndpointsConfigurer
     *
     * @param clients
     * @throws Exception
     */
    //用来配置客户端详情服务，客户端详情信息在这里进行初始化，
    //你能够把客户端详情信息写死在这里或者是通过数据库来存储抽取详情信息
    //授权码模式 http://localhost:53020/uaa/oauth/authorize?client_id=c1&response_type=code&scope=all&redirect_uri=http://www.baidu.com
    ///简化模式 http://localhost:53020/uaa/oauth/authorize?client_id=c1&response_type=token&scope=all&redirect_uri=http://www.baidu.com
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.withClientDetails(clientDetailsService)
                //clients.inMemory()//使用in-memory存储
                .withClient("c1")//client_id
                .secret(new BCryptPasswordEncoder().encode("secret"))//客户端秘钥
                .resourceIds("res1")//客户端可访问资源的id
                //该client允许的授权类型--授权码模式、密码、客户端模式、简化简要模式、刷新令牌模式
                .authorizedGrantTypes("authorization_code","password","client_credentials","implicit","refresh_token")
                .scopes("all")//允许的授权范围
                .autoApprove(false)//授权码模式会跳转授权页面  false会跳转，true不会跳转   这个只有授权码模式用
                //加上验证回调地址
                .redirectUris("http://www.baidu.com");
        //上面是一个客户端，如果在配置第二个客户端
//             .and()
//                .withClient("c1")//client_id
//                .secret(new BCryptPasswordEncoder().encode("secret"))//客户端秘钥
//                .resourceIds("res1")//客户端可访问资源的id
//                //该client允许的授权类型--授权码模式、密码、客户端模式、简化简要模式、刷新令牌模式
//                .authorizedGrantTypes("authorization_code","password", "client_credentials","implicit","refresh_token")
//                .scopes("all")//允许的授权范围
//                .autoApprove(false)//授权码模式会跳转授权页面  false会跳转，true不会跳转   这个只有授权码模式用
//                //加上验证回调地址
//                .redirectUris("http://www.baidu.com");

    }
    //访问端点和令牌服务  用来配置token的访问端点和令牌服务
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)//授权认证管理器
                .authorizationCodeServices(authorizationCodeServices)//授权码服务
                .tokenServices(tokenService())//令牌管理服务
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

    //令牌约束，访问url  用来配置令牌端点的安全约束
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()") //公有秘钥的端点 oauth/token_key是公开的
                .checkTokenAccess("permitAll") //oauth/check_token公开
                .allowFormAuthenticationForClients(); //表单认证（申请令牌）
    }


    //配置token--令牌管理服务
    @Bean
    public AuthorizationServerTokenServices tokenService(){
        DefaultTokenServices service=new DefaultTokenServices();
        service.setClientDetailsService(clientDetailsService);//客户端详情服务
        service.setSupportRefreshToken(true);//支持刷新令牌
        service.setTokenStore(tokenStore);//令牌存储策略--这里是基于内存管理
        //令牌增强
        TokenEnhancerChain tokenEnhancerChain=new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        service.setTokenEnhancer(tokenEnhancerChain);
        service.setAccessTokenValiditySeconds(7200);//令牌默认有效期2小时
        service.setRefreshTokenValiditySeconds(259200);//刷新令牌默认有效期3天
        return service;
    }

    /*//设置授权码模式的授权码如何存取，暂时采用内存方式
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() { //设置授权码模式的授权码如何存取，暂时采用内存方式
        return new InMemoryAuthorizationCodeServices();
    }
*/

    //授权码存储到数据库
    @Bean
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource){
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    //ClientDetailsService和AuthorizationCodeServices从数据库读取数据。
    //将客户端的信息存储到数据库
    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource) {
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        ((JdbcClientDetailsService)
                clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }


}
